﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.ComponentModel;
using System.Net.Sockets;

namespace EkspSys.Network
{
    class HostnameResolver
    {
        private BackgroundWorker hostnameResolverWorker = new BackgroundWorker();

        private IPAddress addr;

        public delegate void HostNameResolvedHandler(string hostname);
        public event HostNameResolvedHandler HostnameResolvedEvent;

        public HostnameResolver(IPAddress addr)
        {
            this.addr = addr;

            // Start hostname lookup in background
            hostnameResolverWorker.WorkerReportsProgress = true;
            hostnameResolverWorker.ProgressChanged += new ProgressChangedEventHandler(AddressResolved);
            hostnameResolverWorker.DoWork += new DoWorkEventHandler(ResolveAddress);
            hostnameResolverWorker.RunWorkerAsync();
        }

        private void AddressResolved(object sender, ProgressChangedEventArgs e)
        {
            if (HostnameResolvedEvent != null)
                HostnameResolvedEvent(e.UserState as string);
        }

        private void ResolveAddress(object sender, DoWorkEventArgs e)
        {
            string hostname = "NA";
            try
            {
                IPHostEntry entry = Dns.GetHostEntry(addr);
                hostname = entry.HostName;
            }
            catch (SocketException _)
            {
                // Failed to lookup hostname
            }

            hostnameResolverWorker.ReportProgress(0, hostname);
        }
    }
}
